/*package itsm.isperp.framework.message.impl;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.UploadInfo;
import itsm.isperp.framework.security.encoding.MD5Helper;
import itsm.isperp.framework.service.UploadFileService;
import itsm.isperp.framework.utils.FileUploadUtils;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.utils.HtmlUtil;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.app.AppUploadFile;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.incident.IcdIncident;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.workflow.service.BpmProcessRunService;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.mail.Message;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.PropertySet;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.BodyType;
import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName;
import microsoft.exchange.webservices.data.core.enumeration.search.SortDirection;
import microsoft.exchange.webservices.data.core.service.folder.Folder;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.core.service.item.Item;
import microsoft.exchange.webservices.data.core.service.schema.ItemSchema;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.Attachment;
import microsoft.exchange.webservices.data.property.complex.AttachmentCollection;
import microsoft.exchange.webservices.data.property.complex.FileAttachment;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import microsoft.exchange.webservices.data.search.FindItemsResults;
import microsoft.exchange.webservices.data.search.ItemView;
import microsoft.exchange.webservices.data.search.filter.SearchFilter;

import org.springframework.jdbc.core.JdbcTemplate;

import com.sun.mail.pop3.POP3Folder;

public class EmailExchangeReader {

  private String mailServer = "mail.mo-co.com";
  private String user = "it.service";
  private String password = "Epo@8888";

  public void read() throws Exception {
    this.readMail();
  }

  public void readMail() throws Exception {
    System.out.print("==收件==");
    ExchangeService service = new ExchangeService(
        ExchangeVersion.Exchange2007_SP1);
    String user = ContextHolder.getConfigByKey("readMailUser"), pwd = ContextHolder
        .getConfigByKey("readMailPassword");
    ExchangeCredentials credentials = new WebCredentials(user, pwd, "mo-co");
    service.setCredentials(credentials);
    service.setTraceEnabled(true);
    try {
      service.setUrl(new URI("https://mail.mo-co.com/EWS/Exchange.asmx"));
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
    Store store = null;

    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");
    IcdIncidentService icdIncidentService = ContextHolder
        .getSpringBean("icdIncidentService");
    bpmProcessRunService = ContextHolder.getSpringBean("bpmProcessRunService");
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");
    // boolean delete = false;
    try {

      Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
      // 获取文件总数量
      int count = inbox.getTotalCount();
      // 循环获取邮箱邮件
      ItemView view = new ItemView(count);
      SearchFilter searchFilter = null;
      // 按照时间顺序收取
      view.getOrderBy().add(ItemSchema.DateTimeReceived,
          SortDirection.Descending);
      FindItemsResults<Item> findResults;
      if (searchFilter == null) {
        findResults = service.findItems(inbox.getId(), view);
      } else {
        // e.g. new SearchFilter.SearchFilterCollection(
        // LogicalOperator.Or, new
        // SearchFilter.ContainsSubstring(ItemSchema.Subject, "EWS"),
        // new SearchFilter.ContainsSubstring(ItemSchema.Subject, "API"))
        findResults = service.findItems(inbox.getId(), searchFilter, view);
      }
      service.loadPropertiesForItems(findResults,
          PropertySet.FirstClassProperties);
      for (Item item : findResults.getItems()) {
        EmailMessage message = (EmailMessage) item;

        Date sdt = message.getDateTimeReceived();
        Date now = new Date();
        int diffDay = daysBetween(sdt, now);
        if (diffDay > 2)
          continue;
        String mid = message.getInternetMessageId();
        mid=MD5Helper.encrypt(mid);
        String address = message.getFrom().getAddress();
        if (!checkIfExistsEmail(mid)) {
          IcdIncident icd = new IcdIncident();
          icd.setSource("邮件");
          icd.setMailId(mid);
          if (message.getSubject() != null)
            icd.setTitle(MimeUtility.decodeText(message.getSubject()));

          String descriptionHtml = message.getBody().toString();
          String description = HtmlUtil.Html2Text(descriptionHtml);
          icd.setDescription(description);
          icd.setDescriptionHtml(descriptionHtml);

          JqGridRequest req = new JqGridRequest();
          req.addFilterRule("email", JqGridFilterRuleOp.eq, address);
          req.isQueryOne(true);
          List<AppUser> us = appUserService.findAll(req);
          if (us != null && us.size() > 0) {
            icd.setCusUserId(us.get(0).getId());

          } else {
            icd.setCusUserId("000");
            icd.setTitle("未知用户[" + address + "]" + icd.getTitle());
          }
          icdIncidentService.saveOrUpdate(icd);

          String id = icd.getId();

          bpmProcessRunService.startProcess("admin", "incidentProcess", id,
              "邮件报障");
          if (isContainAttach(message))
            saveAttachMent(message, id);
        }
      }

    } catch (Exception ex) {
      System.err.println("不能以读写方式打开邮箱!");
      ex.printStackTrace();
    } finally {
      // 释放资源
      try {
        if (store != null)
          store.close();
      } catch (Exception bs) {
        bs.printStackTrace();
      }

    }

  }

  public EmailExchangeReader(String mailServer, String user, String password) {
    this.mailServer = mailServer;
    this.user = user;
    this.password = password;
  }

  public EmailExchangeReader() {
    // TODO Auto-generated constructor stub
  }

  public static void main(String[] args) throws Exception {
    String[] to = { "526932128@qq.com" };
    EmailExchangeReader mail = new EmailExchangeReader("mail.mo-co.com",
        "it.service", "mailServer");
    mail.doSend("test1", to, null, "test1", null);
  }

  public static String Html2Text(String inputString) {
    String htmlStr = inputString; // 含html标签的字符串
    String textStr = "";
    java.util.regex.Pattern p_script;
    java.util.regex.Matcher m_script;
    java.util.regex.Pattern p_style;
    java.util.regex.Matcher m_style;
    java.util.regex.Pattern p_html;
    java.util.regex.Matcher m_html;

    try {
      String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
                                                                                               // }
      String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
                                                                                            // }
      String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

      p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
      m_script = p_script.matcher(htmlStr);
      htmlStr = m_script.replaceAll(""); // 过滤script标签

      p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
      m_style = p_style.matcher(htmlStr);
      htmlStr = m_style.replaceAll(""); // 过滤style标签

      htmlStr = htmlStr.replace("<br>", "\n");

      p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
      m_html = p_html.matcher(htmlStr);
      htmlStr = m_html.replaceAll(""); // 过滤html标签

      textStr = htmlStr;
    } catch (Exception e) {
      // Manager.log.debug("neiNewsAction","Html2Text: " + e.getMessage());
    }
    textStr = textStr.replace("&nbsp;", " ").replace("&quot;", " ")
        .replace("&lt;", "<").replace("&gt;", ">");
    return textStr;// 返回文本字符串
  }

  *//**
   * 发送带附件的mail
   *//*
  public void doSend(String subject, String[] to, String[] cc, String bodyText,
      String[] attachmentPath) throws Exception {
    ExchangeService service = new ExchangeService(
        ExchangeVersion.Exchange2007_SP1);
    ExchangeCredentials credentials = new WebCredentials("it.service",
        "Epo@8888", "mo-co");
    service.setCredentials(credentials);
    service.setTraceEnabled(true);
    try {
      service.setUrl(new URI("https://mail.mo-co.com/EWS/Exchange.asmx"));
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
    // 获取文件总数量
    int count = inbox.getTotalCount();
    if (10 > 0) {
      count = count > 10 ? 10 : count;
    }
    // 循环获取邮箱邮件
    ItemView view = new ItemView(count);
    SearchFilter searchFilter = null;
    // 按照时间顺序收取
    view.getOrderBy()
        .add(ItemSchema.DateTimeReceived, SortDirection.Descending);
    FindItemsResults<Item> findResults;
    if (searchFilter == null) {
      findResults = service.findItems(inbox.getId(), view);
    } else {
      // e.g. new SearchFilter.SearchFilterCollection(
      // LogicalOperator.Or, new
      // SearchFilter.ContainsSubstring(ItemSchema.Subject, "EWS"),
      // new SearchFilter.ContainsSubstring(ItemSchema.Subject, "API"))
      findResults = service.findItems(inbox.getId(), searchFilter, view);
    }
    service.loadPropertiesForItems(findResults,
        PropertySet.FirstClassProperties);
    ArrayList<EmailMessage> result = new ArrayList<>();
    for (Item item : findResults.getItems()) {
      EmailMessage message = (EmailMessage) item;
      result.add(message);
    }

    // ==============================================//

    EmailMessage msg = new EmailMessage(service);
    msg.setSubject(subject);
    MessageBody body = MessageBody.getMessageBodyFromText(bodyText);
    body.setBodyType(BodyType.HTML);
    msg.setBody(body);
    for (String s : to) {
      msg.getToRecipients().add(s);
    }
    if (cc != null) {
      for (String s : cc) {
        msg.getCcRecipients().add(s);
      }
    }
    if (attachmentPath != null && attachmentPath.length > 0) {
      for (int a = 0; a < attachmentPath.length; a++) {
        msg.getAttachments().addFileAttachment(attachmentPath[a]);
      }

    }
    // msg.send();
    System.out.print("ok");
  }

  *//**
   * 发送不带附件的mail
   *//*
  public void send(String subject, String[] to, String[] cc, String bodyText)
      throws Exception {
    doSend(subject, to, cc, bodyText, null);
  }

  public static int daysBetween(Date date1, Date date2) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date1);
    long time1 = cal.getTimeInMillis();
    cal.setTime(date2);
    long time2 = cal.getTimeInMillis();
    long between_days = (time2 - time1) / (1000 * 3600 * 24);

    return Integer.parseInt(String.valueOf(between_days));
  }

  public boolean checkIfExistsEmail(String msgId) {
    String sql = "select *  from icd_incident where mail_id='" + msgId
        + "' and source='邮件'";
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
    if (list.size() > 0) {
      return true;
    } else {
      return false;
    }

  }

  public static boolean isContainAttach(EmailMessage message) throws Exception {
    boolean attachflag = false;
    int count = message.getAttachments().getCount();
    if (count > 0)
      attachflag = true;
    return attachflag;
  }

  public static void saveAttachMent(EmailMessage message, String id)
      throws Exception {
    AttachmentCollection atcm = message.getAttachments();
    List<Attachment> atcmList = atcm.getItems();
    for (Attachment at : atcmList) {
      at.load();
      FileAttachment f = (FileAttachment) at;
      UploadInfo uploadInfo = new AppUploadFile();
      byte[] byt = f.getContent();
      InputStream input = new ByteArrayInputStream(byt);
      uploadInfo.setId(HibernateUUIDGenerator.generate());
      uploadInfo.setExt("png");
      uploadInfo.setSourceId(id);
      uploadInfo.setContentType(f.getContentType());
      uploadInfo.setName(f.getName());
      FileUploadUtils.persist(input, uploadInfo);
      UploadFileService<UploadInfo> uploadFileService = ContextHolder
          .getSpringBean("appUploadFileService");
      uploadFileService.saveOrUpdate(uploadInfo);
    }
  }

  public ArrayList<EmailMessage> receive(int max, SearchFilter searchFilter)
      throws Exception {
    ExchangeService service = new ExchangeService(
        ExchangeVersion.Exchange2007_SP1);
    ExchangeCredentials credentials = new WebCredentials(user, password);
    service.setCredentials(credentials);
    service.setUrl(new URI(mailServer));
    // 绑定收件箱,同样可以绑定发件箱
    Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
    // 获取文件总数量
    int count = inbox.getTotalCount();
    if (max > 0) {
      count = count > max ? max : count;
    }
    // 循环获取邮箱邮件
    ItemView view = new ItemView(count);
    // 按照时间顺序收取
    view.getOrderBy()
        .add(ItemSchema.DateTimeReceived, SortDirection.Descending);
    FindItemsResults<Item> findResults;
    if (searchFilter == null) {
      findResults = service.findItems(inbox.getId(), view);
    } else {
      // e.g. new SearchFilter.SearchFilterCollection(
      // LogicalOperator.Or, new
      // SearchFilter.ContainsSubstring(ItemSchema.Subject, "EWS"),
      // new SearchFilter.ContainsSubstring(ItemSchema.Subject, "API"))
      findResults = service.findItems(inbox.getId(), searchFilter, view);
    }
    service.loadPropertiesForItems(findResults,
        PropertySet.FirstClassProperties);
    ArrayList<EmailMessage> result = new ArrayList<>();
    for (Item item : findResults.getItems()) {
      EmailMessage message = (EmailMessage) item;
      result.add(message);
    }
    return result;
  }
}*/